"""
Phase 4: KAOPEN Gating
========================
Tests whether capital account openness differentially gates gross vs net channels:
  Table 6: Z + Z×KAOPEN → gross_assets, gross_liab, gross_ifi, nfa, ca, income_bal
  Table 7: Z + Z×KAOPEN → each instrument (assets + liabs separately)

Key test: Z₁×KAOPEN > 0 on gross_ifi (openness amplifies gross)
          Z₁×KAOPEN ≤ 0 on ca_gdp (dampens net)
"""

import pandas as pd
import numpy as np
from pathlib import Path
import sys
import warnings
warnings.filterwarnings('ignore')

PROJECT_DIR = Path(__file__).resolve().parent.parent
ROOT_DIR = PROJECT_DIR.parent
sys.path.insert(0, str(ROOT_DIR / "multilateral" / "src"))
from model import PanelGLS

DATA = PROJECT_DIR / "data" / "processed"
OUT_TABLES = PROJECT_DIR / "output" / "tables"
OUT_TABLES.mkdir(parents=True, exist_ok=True)

DEMO_VARS = ['Z_1', 'Z_2', 'Z_3']
EBA_CONTROLS = ['fiscal_bal_gdp', 'nfa_gdp_lag', 'log_rel_opw', 'kaopen']
INTERACTION_VARS = ['Z_1_x_kaopen', 'Z_2_x_kaopen', 'Z_3_x_kaopen']


def stars(p):
    if p < 0.01: return '***'
    if p < 0.05: return '**'
    if p < 0.1: return '*'
    return ''


def fmt(val, se, p):
    return f"{val:.4f}{stars(p)}", f"({se:.4f})"


def run_gls(df, y_var, x_vars, label):
    cols = [y_var] + x_vars + ['iso3', 'year']
    sub = df[cols].dropna()
    if len(sub) < 50:
        print(f"  SKIP {label}: only {len(sub)} obs")
        return None

    gls = PanelGLS()
    gls.fit(sub[y_var].values, sub[x_vars].values,
            sub['iso3'].values, sub['year'].values)

    result = {
        'model': label, 'dep_var': y_var,
        'n_obs': gls.n_obs, 'n_countries': gls.n_countries,
        'r_squared': gls.r_squared, 'rho': gls.rho,
    }
    for i, name in enumerate(x_vars):
        result[f'{name}_coef'] = gls.beta[i]
        result[f'{name}_se'] = gls.se[i]
        result[f'{name}_p'] = gls.pvalues[i]

    print(f"\n  {label} (N={gls.n_obs}, R²={gls.r_squared:.4f})")
    for i, name in enumerate(x_vars):
        if 'Z_' in name or 'kaopen' in name.lower():
            sig = stars(gls.pvalues[i])
            print(f"    {name:25s} {gls.beta[i]:10.4f} ({gls.se[i]:.4f}) {sig}")

    return result


def write_table(results, filename, title, key_vars=None):
    if not results:
        return

    lines = [f"# {title}\n"]

    if key_vars is None:
        key_vars = []
        for r in results:
            for k in r:
                if k.endswith('_coef'):
                    v = k.replace('_coef', '')
                    if v not in key_vars:
                        key_vars.append(v)

    model_labels = [r['model'] for r in results]
    header = "| Variable | " + " | ".join(model_labels) + " |"
    sep = "|:---|" + "|".join(["---:" for _ in results]) + "|"
    lines.append(header)
    lines.append(sep)

    for var in key_vars:
        coef_row = f"| {var} |"
        se_row = "| |"
        for r in results:
            if f'{var}_coef' in r:
                c, s = fmt(r[f'{var}_coef'], r[f'{var}_se'], r[f'{var}_p'])
                coef_row += f" {c} |"
                se_row += f" {s} |"
            else:
                coef_row += " |"
                se_row += " |"
        lines.append(coef_row)
        lines.append(se_row)

    lines.append("|:---|" + "|".join(["---:" for _ in results]) + "|")
    for stat, key, fmt_str in [('Dep var', 'dep_var', '{}'), ('N', 'n_obs', '{}'),
                                ('R²', 'r_squared', '{:.4f}'),
                                ('Countries', 'n_countries', '{}')]:
        row = f"| {stat} |"
        for r in results:
            row += f" {fmt_str.format(r[key])} |"
        lines.append(row)

    lines.append("\n*Panel GLS with AR(1) errors. Standard errors in parentheses.*")
    lines.append("*\\*p<0.1, \\*\\*p<0.05, \\*\\*\\*p<0.01*")

    path = OUT_TABLES / filename
    path.write_text('\n'.join(lines))
    print(f"\n  Saved: {path}")


def main():
    print("=" * 70)
    print("PHASE 4: KAOPEN GATING")
    print("=" * 70)

    df = pd.read_csv(DATA / "net_gross_panel.csv")
    df = df[df['year'] <= 2024].copy()
    print(f"Panel: {len(df)} obs, {df['iso3'].nunique()} countries")

    controls = [c for c in EBA_CONTROLS if c in df.columns and df[c].notna().sum() > 200]

    # Ensure interaction terms exist
    for z in ['Z_1', 'Z_2', 'Z_3']:
        col = f'{z}_x_kaopen'
        if col not in df.columns and 'kaopen' in df.columns:
            df[col] = df[z] * df['kaopen']

    interactions = [c for c in INTERACTION_VARS if c in df.columns]
    ext_vars = DEMO_VARS + controls + interactions

    # ══════════════════════════════════════════════════════════════════
    # TABLE 6: Z×KAOPEN on Aggregate Positions + CA + Income Balance
    # ══════════════════════════════════════════════════════════════════
    print("\n" + "=" * 50)
    print("TABLE 6: KAOPEN GATING — AGGREGATE")
    print("=" * 50)

    results_t6 = []
    dvs = ['gross_assets_gdp', 'gross_liab_gdp', 'gross_ifi',
           'nfa_gdp', 'ca_gdp', 'income_balance_gdp']
    dvs = [v for v in dvs if v in df.columns and df[v].notna().sum() > 200]

    for dep in dvs:
        short = dep.replace('_gdp', '').replace('balance_', '')
        r = run_gls(df, dep, ext_vars, short)
        if r: results_t6.append(r)

    write_table(results_t6, "kaopen_gating_aggregate.md",
                "Table 6: KAOPEN Gating — Demographics × Capital Openness",
                key_vars=DEMO_VARS + interactions + controls)

    # ══════════════════════════════════════════════════════════════════
    # TABLE 7: Z×KAOPEN by Instrument
    # ══════════════════════════════════════════════════════════════════
    print("\n" + "=" * 50)
    print("TABLE 7: KAOPEN GATING — BY INSTRUMENT")
    print("=" * 50)

    results_t7 = []
    instruments = ['fdi_assets_gdp', 'fdi_liab_gdp', 'port_eq_assets_gdp',
                   'debt_assets_gdp', 'debt_liab_gdp', 'fx_reserves_gdp']
    instruments = [v for v in instruments if v in df.columns and df[v].notna().sum() > 200]

    for dep in instruments:
        short = dep.replace('_gdp', '')
        r = run_gls(df, dep, ext_vars, short)
        if r: results_t7.append(r)

    write_table(results_t7, "kaopen_gating_instruments.md",
                "Table 7: KAOPEN Gating by Instrument Type",
                key_vars=DEMO_VARS + interactions)

    # ══════════════════════════════════════════════════════════════════
    # TABLE 6b: KAOPEN Gating — Excl Financial Centers
    # ══════════════════════════════════════════════════════════════════
    FINANCIAL_CENTERS = ['LUX', 'IRL', 'HKG', 'SGP', 'CHE', 'NLD', 'BEL']
    df_nofc = df[~df['iso3'].isin(FINANCIAL_CENTERS)].copy()
    print("\n" + "=" * 50)
    print("TABLE 6b: KAOPEN GATING — EXCL FINANCIAL CENTERS")
    print("=" * 50)
    print(f"  Excl FC: {len(df_nofc)} obs, {df_nofc['iso3'].nunique()} countries")

    results_t6b = []
    for dep in dvs:
        short = f'ExFC: {dep.replace("_gdp", "").replace("balance_", "")}'
        r = run_gls(df_nofc, dep, ext_vars, short)
        if r: results_t6b.append(r)

    write_table(results_t6b, "kaopen_gating_aggregate_exfc.md",
                "Table 6b: KAOPEN Gating — Excl Financial Centers",
                key_vars=DEMO_VARS + interactions + controls)

    # ══════════════════════════════════════════════════════════════════
    # TABLE 6c: KAOPEN Gating — Winsorized
    # ══════════════════════════════════════════════════════════════════
    print("\n" + "=" * 50)
    print("TABLE 6c: KAOPEN GATING — WINSORIZED")
    print("=" * 50)

    dvs_w = [f'{v}_w' for v in ['gross_assets_gdp', 'gross_liab_gdp', 'gross_ifi']
             if f'{v}_w' in df.columns]
    dvs_w += [v for v in ['ca_gdp', 'income_balance_gdp'] if v in df.columns]

    results_t6c = []
    for dep in dvs_w:
        short = f'Win: {dep.replace("_gdp", "").replace("_w", "").replace("balance_", "")}'
        r = run_gls(df, dep, ext_vars, short)
        if r: results_t6c.append(r)

    if results_t6c:
        write_table(results_t6c, "kaopen_gating_aggregate_winsorized.md",
                    "Table 6c: KAOPEN Gating — Winsorized Gross Positions",
                    key_vars=DEMO_VARS + interactions)

    # ══════════════════════════════════════════════════════════════════
    # SIGN-FLIP TEST: Z₁×KAOPEN on gross vs net
    # ══════════════════════════════════════════════════════════════════
    print("\n" + "=" * 50)
    print("SIGN-FLIP TEST: Z₁×KAOPEN")
    print("=" * 50)

    all_r = results_t6 + results_t7 + results_t6b + results_t6c
    for r in all_r:
        if 'Z_1_x_kaopen_coef' in r:
            sig = stars(r['Z_1_x_kaopen_p'])
            print(f"  {r['model']:35s}  Z₁×KAOPEN = {r['Z_1_x_kaopen_coef']:8.4f} "
                  f"(p={r['Z_1_x_kaopen_p']:.4f}) {sig}")

    print("\n" + "=" * 70)
    print("PHASE 4 COMPLETE")
    print("=" * 70)


if __name__ == '__main__':
    main()
